package com.crm.web.controller;

import com.crm.entity.Dict;
import com.crm.service.DictService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/dict")
public class DictController {

    @Resource
    DictService dictService;

    @RequestMapping("/list")
    public String list(@RequestParam(required = false, defaultValue = "") Integer dictId,
                       @RequestParam(required = false, defaultValue = "") String dictValue,
                       @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                       Model model) {
        Sort sort = new Sort(Sort.Direction.ASC, "dictId");
        Pageable pageable = PageRequest.of(pageIndex - 1, 3, sort);
        Page<Dict> page = dictService.findByDictIdAndAndDictValue(dictId,dictValue,pageable);
        model.addAttribute("dictPage", page);
        model.addAttribute("dictId", dictId);
        model.addAttribute("dictValue", dictValue);
        return "dict/list";
    }

    @RequestMapping("/save")
    public String save(Dict dict) {
        try {
            dictService.save(dict);
            return "redirect:/dict/list";
        } catch (Exception e) {
            return "dict/add";
        }
    }

    @RequestMapping("/edit")
    public String edit(@RequestParam Integer dictId, Model model) {
        model.addAttribute("dict", dictService.getDictByDictId(dictId));
        return "dict/edit";
    }

    @RequestMapping("/add")
    public String add() {
        return "dict/add";
    }

    @RequestMapping("/del/{dictId}")
    @ResponseBody
    public Map del(@PathVariable Integer dictId) {
        Map map = new HashMap<>();
        try {
            dictService.del(dictId);
            map.put("delResult", "true");
        } catch (Exception e) {
            map.put("delResult", "false");
        }
        return map;
    }
}
